<template>
  <div class="word-lookup-wrapper">
    <slot></slot>

    <!-- 查词菜单 -->
    <div
      v-show="showLookupMenu"
      class="lookup-menu"
      :style="{ top: lookupMenuY + 'px', left: lookupMenuX + 'px' }"
      @click="lookupSelectedWord"
    >
      <el-icon><Search /></el-icon>
      <span>查词</span>
    </div>

    <!-- 单词详情对话框 -->
    <WordDetailDialog
      :showMarkWordButton="true"
      :visible="showWordDetailDialog"
      :word="selectedWord"
      :show-mark-word-button="true"
      :is-marked="isWordMarked"
      @update:visible="showWordDetailDialog = $event"
      @close="closeWordDetail"
      @toggle-word-mark="handleToggleWordMark"
    />
  </div>
</template>

<script>
import WordDetailDialog from '@/components/vocabulary/WordDetailDialog.vue'
import http from '@/utils/http'
import { isLoggedIn } from '@/utils/auth'
import { Search } from '@element-plus/icons-vue'
export default {
  name: 'WordLookup',
  components: {
    WordDetailDialog,
    Search
  },
  props: {
    // 移除了外部传入的markedWords属性
  },
  emits: ['toggle-word-mark'],
  data() {
    return {
      showWordDetailDialog: false,
      selectedWord: null,
      isWordMarked: false,
      showLookupMenu: false,
      lookupMenuX: 0,
      lookupMenuY: 0,
      selectedText: ''
    }
  },
  mounted() {
    // 在组件挂载时添加document事件监听器
    document.addEventListener('mouseup', this.handleTextSelection)
    document.addEventListener('click', this.hideLookupMenu)
    document.addEventListener('keydown', this.hideLookupMenu)
  },
  beforeUnmount() {
    // 在组件卸载前移除事件监听器
    document.removeEventListener('mouseup', this.handleTextSelection)
    document.removeEventListener('click', this.hideLookupMenu)
    document.removeEventListener('keydown', this.hideLookupMenu)
  },
  methods: {
    getMousePosition(e) {
      return {
        x: e.clientX,
        y: e.clientY
      }
    },
    handleTextSelection(e) {
      setTimeout(() => {
        // 获取选中的文本
        const selection = window.getSelection()
        const selectedText = selection.toString().trim()

        // 如果没有选中文字或选中文字包含空格，则不处理
        if (!selectedText || selectedText.includes(' ') || selectedText.length === 0) {
          this.hideLookupMenu()
          return
        }

        // 如果选中的单词包含非英文字符，则不处理
        if (/[^\w\s]/.test(selectedText)) {
          this.hideLookupMenu()
          return
        }

        // 获取鼠标相对于浏览器窗口的坐标
        const { x, y } = this.getMousePosition(e)

        // 显示查词菜单
        this.showLookupMenu = true
        this.lookupMenuX = x
        this.lookupMenuY = y - 20 // 在选中文本上方显示

        // 保存选中的文本
        this.selectedText = selectedText
      }, 200)
    },

    hideLookupMenu() {
      this.showLookupMenu = false
    },

    async lookupSelectedWord() {
      // 隐藏查词菜单
      this.showLookupMenu = false

      // 设置选中的单词
      this.selectedWord = { vocabulary: this.selectedText }

      // 检查单词是否已经被标记为生词
      await this.checkIfWordMarked(this.selectedText)

      // 显示单词详情对话框
      this.showWordDetailDialog = true

      // 清除选择
      window.getSelection().removeAllRanges()
    },

    async checkIfWordMarked(word) {
      // 在组件内部查询单词是否为生词
      if (!isLoggedIn()) {
        this.isWordMarked = false
        return
      }

      try {
        const response = await http.get(`/vocabulary/user/${word.toLowerCase()}`)

        // 如果成功获取到单词信息，则认为是已标记的生词
        this.isWordMarked = response?.everMarked
      } catch (err) {
        // 如果出现错误（如404），则认为不是生词
        this.isWordMarked = false
      }
    },

    closeWordDetail() {
      this.showWordDetailDialog = false
      this.selectedWord = null
    },

    async handleToggleWordMark(wordData) {
      // 在组件内部实现标记/取消标记生词的逻辑
      if (!isLoggedIn()) {
        return
      }

      try {
        await http.post(`/vocabulary/user`, {
          is_favorite: false,
          is_learned: this.isWordMarked,
          word: wordData.word.toLowerCase()
        })
        this.isWordMarked = !this.isWordMarked
        this.$message.success(this.isWordMarked ? '已添加生词' : '已取消生词标记')

        // 同时更新父组件
        this.$emit('toggle-word-mark', { word: wordData.word, isMarked: this.isWordMarked })
      } catch (err) {
        console.error('Failed to toggle word mark:', err)
        this.$message.error(this.isWordMarked ? '取消标记失败' : '添加生词失败')
      }
    }
  }
}
</script>

<style scoped>
.word-lookup-wrapper {
  display: inline;
  z-index: 9999;
}

.lookup-menu {
  position: absolute;
  background-color: #ff6c37;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
  padding: 4px 12px;
  color: white;
  cursor: pointer;
  z-index: 9999;
  user-select: none;
  display: flex;
  align-items: center;
  gap: 4px;
}

.lookup-menu:hover {
  background-color: #334d66;
}
</style>